package main

import (
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2/bson"
)

func ChapterRouterInit(r *gin.Engine) {
	r.POST("/chapter/create", CreateChapterApi)     // 创建章节
	r.GET("/chapter/get", GetChapterApi)            // 获取章节
	r.POST("/chapter/update", UpdateChapterApi)     // 更新章节
	r.GET("/chapter/delete", DeleteChapterApi)      // 删除章节
	r.GET("/chapter/list", GetChapterListByPageApi) // 获取章节列表
	r.GET("/chapter/last", GetChaptersLast)         //从后获取章节列表
}

// create chapter by book id and chapter name
func CreateChapterApi(c *gin.Context) {
	var chapter Chapter
	err := c.ShouldBindJSON(&chapter)
	fmt.Println(chapter)
	if err != nil {
		Error(c, 1, err.Error())
		return
	}

	err = CreateChapter(&chapter)
	if err != nil {
		Error(c, 1, err.Error())
		return
	}
	Ok(c)
}

// 分页查询章节列表
func GetChapterListByPageApi(c *gin.Context) {
	bookId := c.Query("bookId")
	if bookId == "" || bookId == "undefined" {
		Error(c, 1, "Book ID is required")
		return
	}
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	if page == 0 {
		page = 1
	}
	if pageSize == 0 {
		pageSize = 10
	}
	chapters, total, err := GetChaptersList(bookId, page, pageSize)
	if err != nil {
		Error(c, 1, "Book not found")
	}
	SuccessPage(c, chapters, total, page, pageSize)
}

// get chapter by id
func GetChapterApi(c *gin.Context) {
	//userId := c.GetString("user_id")
	chapterId := c.Query("id")
	chapter, err := GetChapter(chapterId)
	if err != nil {
		Error(c, 1, "Chapter not found")
		return
	}
	Success(c, chapter)
}

// update chapter by id and chapter name
func UpdateChapterApi(c *gin.Context) {
	var chapter Chapter
	if err := c.ShouldBindJSON(&chapter); err != nil {
		Error(c, 1, err.Error())
		return
	}
	//检查组chapter的数据，如果存在则放入bson.M中，否则不放入，防止更新空值，导致数据丢失，影响数据库
	updateFields := bson.M{}
	if chapter.Name != "" {
		updateFields["name"] = chapter.Name
	}
	if chapter.Content != "" {
		updateFields["content"] = chapter.Content
	}
	if chapter.Summary != "" {
		updateFields["summary"] = chapter.Summary
	}
	err := UpdateChapter(chapter.ID.Hex(), updateFields)
	if err != nil {
		Error(c, 1, err.Error())
		return
	}
	Ok(c)
}

// delete chapter by id
func DeleteChapterApi(c *gin.Context) {
	chapterId := c.Query("id")
	err := DeleteChapter(chapterId)
	if err != nil {
		Error(c, 1, "删除失败")
		return
	}
	Ok(c)
}

func GetChaptersLast(c *gin.Context) {
	bookId := c.Query("bookId")
	limit := c.DefaultQuery("limit", "10")
	if bookId == "" || bookId == "undefined" {
		Error(c, 1, "Book ID is required")
		return
	}
	limitInt, err := strconv.Atoi(limit)
	chapter, err := GetChaptersByBookLast(bookId, limitInt)
	if err != nil {
		Error(c, 1, "Chapter not found")
		return
	}
	Success(c, chapter)
}
